package com.yuesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuesystem.common.BaseContext;
import com.yuesystem.entity.CollectBlog;
import com.yuesystem.mapper.CollectBlogMapper;
import com.yuesystem.service.CollectBlogService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 收藏帖子接口实现类.
 */
@Service
@Slf4j
public class CollectBlogServiceImpl
    extends ServiceImpl<CollectBlogMapper, CollectBlog> implements CollectBlogService {

  /**
   * 判断当前用户是否收藏过该帖子.
   *
   * @param blogId 帖子id
   * @return 当前用户是否收藏过该帖子
   */
  @Override
  public Boolean judge(Long blogId) {
    // 获取当前用户id
    Long userId = BaseContext.getCurrentId();

    LambdaQueryWrapper<CollectBlog> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(CollectBlog::getBlogId, blogId).eq(CollectBlog::getUserId, userId);
    CollectBlog one = this.getOne(queryWrapper);
    if (one == null) {
      return false;
    }
    return true;
  }

  /**
   * 根据帖子id统计该帖子的收藏量.
   *
   * @param blogId 帖子id
   * @return 帖子收藏量
   */
  @Override
  public Long getCollectCount(Long blogId) {
    LambdaQueryWrapper<CollectBlog> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(CollectBlog::getBlogId, blogId);
    Long count = this.count(queryWrapper);
    return count;
  }

  /**
   * 取消收藏.
   *
   * @param blogId 帖子id
   */
  @Override
  public void cancel(Long blogId) {
    // 获取当前用户id
    Long userId = BaseContext.getCurrentId();
    LambdaQueryWrapper<CollectBlog> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(CollectBlog::getUserId, userId).eq(CollectBlog::getBlogId, blogId);
    this.remove(queryWrapper);
  }

  /**
   * 添加收藏.
   *
   * @param blogId 帖子id
   */
  @Override
  public void add(Long blogId) {
    // 获取当前用户id
    Long userId = BaseContext.getCurrentId();
    CollectBlog collectBlog = new CollectBlog();
    collectBlog.setUserId(userId);
    collectBlog.setBlogId(blogId);
    this.save(collectBlog);
  }

  /**
   * 根据用户id删除他的所有收藏帖子记录.
   *
   * @param userId 用户id
   */
  @Override
  public void deleteById(Long userId) {
    LambdaQueryWrapper<CollectBlog> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(CollectBlog::getUserId, userId);
    this.remove(queryWrapper);
  }

  /**
   * 根据blog的id删除所有和他有关的收藏.
   *
   * @param listBlog 帖子id列表
   */
  @Override
  public void deleteByBlog(List<Long> listBlog) {
    LambdaQueryWrapper<CollectBlog> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.in(listBlog.size() != 0, CollectBlog::getBlogId, listBlog);
    this.remove(queryWrapper);
  }

}
